<table class="entity-table">
<tr class="spaned">
    <th colspan="3">Faktura</th>
    <th colspan="2" class="second">Uplate</th>
</tr>
<tr>
    <th width="5%">Broj</th>
    <th>Kampanja</th>
    <th class="text-right" width="20%">Iznos</th>
    <th class="second" width="20%">Datum</th>
    <th class="second text-right" width="20%">Iznos</th>
</tr>
<? foreach ($invoices as $invoice): ?>
<?php
    $invoiceId = $invoice['Invoice']['id'];
?>
<tr>
    <td><?= $this->Html->link($invoice['Invoice']['number'], '/invoices/edit/'.$invoiceId) ?></td>
    <td>
        <? if (!empty($invoice['Campaign'])): ?>
        <?= $this->Html->link($invoice['Campaign']['name'], '/campaigns/edit/'.$invoice['Campaign']['id']) ?>
        <? endif ?>
    </td>
    <td class="text-right"><?= currency_format($invoice['Invoice']['amount']) ?></td>
    
    <?php
        $p = @$payments[$invoiceId]; $p = $p ? $p : array();
        $total = 0;
        $exchRate = $invoice['ExchangeRate']['rate'];
        
        @list($first) = array_splice($p, 0, 1);
        $amount = $first['Payment']['amount'] * $exchRate;
        $total += $amount;
    ?>
    <? if (! empty($first)): ?>
        <td class="second"><?= $this->Html->link(date_local($first['Payment']['date']), '/payments/edit/'.$first['Payment']['id']) ?></td>
        <td class="second text-right"><?= currency_format($amount) ?></td>
    <? else: ?>
        <td class="second" colspan="2">Nema uplata.</td>
    <? endif ?>
</tr>

<? foreach ($p as $pay): ?>
<?php
    $amount = $pay['Payment']['amount'] * $exchRate;
    $total += $amount;
?>
<tr>
    <td colspan="3"></td>
    <td class="second"><?= $this->Html->link(date_local($pay['Payment']['date']), '/payments/edit/'.$pay['Payment']['id']) ?></td>
    <td class="second text-right"><?= currency_format($amount) ?></td>
</tr>
<? endforeach ?>
<tr class="total sub">
    <td colspan="5" class="text-right"><?= currency_format($total) ?></td>
</tr>
<? endforeach ?>
</table>
